package com.adam.blog.controller;

import com.adam.blog.utils.QiniuUtils;
import com.adam.blog.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private QiniuUtils qiniuUtils;

    @PostMapping
    public Result upload(@RequestParam("image") MultipartFile file){
        //文件原始名称    xx.jpg
        String originalFilename = file.getOriginalFilename();
        //唯一的文件名称   随机码 + . + 后缀
        String fileName = UUID.randomUUID().toString()+"."+ StringUtils.substringAfter(originalFilename,".");
        //图片上传到七牛云  速度快 减低自身带宽消耗
        boolean upload = qiniuUtils.upload(file, fileName);
        if(upload){
            //注意url格式
            return Result.success("http://"+QiniuUtils.url + "/" + fileName);
        }
        return Result.fail(2001,"上传失败");
    }
}
